<?php

namespace App\Console\Commands;

use App\Library\Logic\ShopImageLogic;
use App\Library\Logic\ShopProductDepositPriceLogic;
use App\Library\Logic\ShopProductLogic;
use App\Library\Logic\ShopProductSpecsLogic;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class ShopProductChangeCommand extends Command
{
    /**
     * 更新订单商品规格
     *
     * @var string
     */
    protected $signature = 'command:shopProductChange {serialNumber}';

    /**
     * 更新订单商品规格
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * handle
     * @throws Exception
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        $shopProduct = ShopProductLogic::findBySerialNumber($serialNumber);
        if (is_null($shopProduct)) return;
        ShopProductSpecsLogic::updateByWhere(['productId' => 0, 'randProductId' => 0], 'productId', $shopProduct->product_id);
        //ShopProductSpecsLogic::bind($shopProduct);
        if (!is_null($shopProduct->spec_json)) {
            foreach ($shopProduct->spec_json as $k => $v) {
                ShopProductSpecsLogic::updateByWhere([
                    'psSort' => $k,
                    'psIsDelete' => 2,
                    'randProductId' => 0,
                    'userId' => $shopProduct->user_id,
                    'productId' => $shopProduct->product_id,
                ], 'psId', (int)cache('shopProductSpec:' . $v));
            }
        }
        //$this->mainImg($shopProduct);
        //$this->descImg($shopProduct);
        ShopProductLogic::editStock($shopProduct);
        $this->deposit($shopProduct);
        $shopProduct->is_commission = ShopProductSpecsLogic::query()->where('product_id', $shopProduct->product_id)
            ->where(function (Builder $query) {
                $query->where('commission', '>', 0)->orWhere('commission_ratio', '>', 0);
            })->exists();
        $shopProduct->buy_will = ShopProductSpecsLogic::query()->where('product_id', $shopProduct->product_id)
            ->where(function (Builder $query) {
                $query->whereNotNull('buy_will_price');
            })->exists();
        $shopProduct->save();
    }

    private function deposit(Model $shopProduct): void
    {
        $price = ShopProductSpecsLogic::valueByWhere([
            'product_id' => $shopProduct->product_id,
            'user_id' => $shopProduct->user_id,
            'orderByDesc' => 'psPrice',
        ], null, 'psPrice');
        $pdpRate = (int)__('base.deposit');//百分比
        $pdpReceivablePrice = 0;

        if (!is_null($price)) $pdpReceivablePrice = bcdiv(bcmul($price, $pdpRate, 2), 100, 2);
        $shopProductDepositPrice = ShopProductDepositPriceLogic::findByWhere('productId', $shopProduct->product_id);
        if (!is_null($shopProductDepositPrice)) {
            $shopProductDepositPrice->pdp_rate = $pdpRate;
            $shopProductDepositPrice->pdp_deposit_price = $pdpReceivablePrice;
            $shopProductDepositPrice->save();
        } else {
            ShopProductDepositPriceLogic::insertForModel([
                'productId' => $shopProduct->product_id,
                'userId' => $shopProduct->user_id,
                'pdpSn' => 'DN' . date('YmdHis') . random(10, 1),
                'pdpRate' => $pdpRate,
                'pdpReceivablePrice' => $pdpReceivablePrice,
            ]);
        }
    }

    private function mainImg(Model $shopProduct): void
    {
        if (is_null($shopProduct->product_avatar_img_id_json)) return;
        $array = json_decode($shopProduct->product_avatar_img_id_json, true);
        if (empty($array)) return;
        ShopImageLogic::query()->where('user_main_id', $shopProduct->user_id)
            ->where(['img_source_type' => 4, 'img_source_id' => $shopProduct->product_id])
            ->update(['img_source_id' => 0, 'img_is_cover' => 2]);
        $list = ShopImageLogic::query()->where('img_source_type', 4)
            ->whereIn('img_id', $array)->orderBy('img_type')->get();
        foreach ($list as $k => $shopImage) {
            $shopImage->img_sort = $k;
            $shopImage->img_is_cover = 2;
            $shopImage->img_source_id = $shopProduct->product_id;
            if ($k === 0) {
                $shopProduct->product_avatar = $shopImage->img_url;
                if (strlen($shopProduct->product_avatar) === 24) {
                    $shopProduct->product_avatar = str_replace('/', '', $shopProduct->product_avatar);
                }
                $shopImage->img_is_cover = 1;
            }
            $shopImage->save();
        }
        $shopProduct->save();
    }

    private function descImg(Model $shopProduct): void
    {
        ShopImageLogic::query()->where('user_main_id', $shopProduct->user_id)
            ->where(['img_source_type' => 5, 'img_source_id' => $shopProduct->product_id])
            ->update(['img_source_id' => 0, 'img_is_cover' => 0]);
        if (is_null($shopProduct->product_content_img_id_json)) return;
        $array = json_decode($shopProduct->product_content_img_id_json, true);
        if (empty($array)) return;
        ShopImageLogic::query()->whereIn('img_id', $array)
            ->where('img_source_type', 5)
            ->update(['img_source_id' => $shopProduct->product_id, 'img_is_cover' => 0]);
        foreach ($array as $k => $v) ShopImageLogic::updateByWhere(['imgSort' => $k], 'imgId', $v);
    }
}
